<?php

declare (strict_types=1);

namespace catchAdmin\monitor\command;

use Carbon\Carbon;
use catchAdmin\basics\model\Company;
use catchAdmin\basics\model\StorageFeeConfig;
use catchAdmin\basics\model\StorageFeeConfigInfo;
use catchAdmin\product\model\Product;
use catchAdmin\settlement\model\StorageFee;
use catchAdmin\settlement\model\StorageProductFee;
use catchAdmin\warehouse\model\WarehouseOrderProducts;
use catchAdmin\warehouse\model\WarehouseStock;
use catchAdmin\warehouse\model\WarehouseStockLogs;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use catcher\Code;
use think\facade\Db;

class FixStorageFeeCommand extends Command {
    protected $pid;

    protected function configure () {
        // 指令配置
        $this->setName('catch:FixStorageFee')
             ->setDescription('修复仓储费历史记录');
    }

    protected function execute (Input $input, Output $output) {
        try {
            $this->executeCommand();
        } catch (\Exception $e) {
            Log::error('StorageFee Error Line:' . $e->getLine());
            Log::error('StorageFee Error Code:' . $e->getCode());
            Log::error('StorageFee Error Message:' . $e->getMessage());
            throw new \Exception($e->getLine() ."----" .$e->getMessage());
        }
    }

    /**
     * 执行 command
     *
     * @time 2021年03月02日
     * @return void
     */
    protected function executeCommand () {
        echo 'start:' .date('H:i:s') . "\r\n";
        $companys = Company::select();


        foreach ($companys as $company) {

            //按公司计算并存储仓储费
            $storageFee = StorageFee::where('company_id', $company->id)->find();
            if (!$storageFee) {
                $storageFee = StorageFee::create([
                                                     'company_id' => $company->id,
                                                     'company_name' => $company->getAttr('name'),
                                                     'company_code' => $company->code,
                                                     'company_type' => $company->type,
                                                 ]);

            }
            echo 'storageFee:' .date('H:i:s') . "\r\n";
            //获取所有商品
            $products = Product::where('company_id', $company->id)->select();

            echo 'products:' .date('H:i:s') . "\r\n";

            foreach ($products as  $product) {

                //获取商品所有批次
                $stock = WarehouseStock::alias('ws')
                                       ->leftJoin('warehouses w', 'w.id=ws.virtual_warehouse_id')
                                       ->where('goods_code',$product->code)
                                       ->where('w.type', '<>', 3)
                                       ->select();
                echo 'stock:' .date('H:i:s') . "\r\n";

                if (count($stock) == 0) {
                    continue;
                }


                //计算每个批次的入库时长
                foreach ($stock as $val) {
                    echo "goods：" .  $val->goods_code . '--' . $val->company_id . "\r\n";
                    $warehousingTime = '';
                    if ($val->number > 0) {
                        $orderProduct = WarehouseOrderProducts::alias('wop')
                        ->leftJoin('warehouse_orders wo', 'wo.id=wop.warehouse_order_id')
                        ->where([
                                    'batch_no' => $val->batch_no,
                                    'goods_code' => $val->goods_code,
                                    'warehousing_status' => 1
                                ])
                        ->find();


                        if ($orderProduct ) {
                            $warehousingTime = $orderProduct->warehousing_time;//入库时间

                        }else {
                            $warehousingTime = '2021-07-10';
                        }


                        $diffDays = Carbon::parse($warehousingTime)->diffInDays();//入库时长

                        //计算仓库费
                        $storageConfig = StorageFeeConfigInfo::alias('sfci')
                                                             ->leftJoin('storage_fee_config sfc', 'sfc.id=sfci.fee_config_id')
                                                             ->where([
                                                                         'sfc.company_id' => $company->id,
                                                                         'sfc.is_status' => 1
                                                                     ])
                                                             ->where('min_days', '<=', $diffDays)
                                                             ->where('max_days', '>=', $diffDays)
                                                             ->where('warehouse_id', 'like', "%" . $val->virtual_warehouse_id . "%")
                                                             ->find();
                        echo 'storageConfig:' .date('H:i:s') . "\r\n";

                        if ($storageConfig && $storageConfig->fee > 0) {

                            //计算每天的仓储费用
                            $days = $diffDays-30;

                            $startDateArray = [];
                            for($i=1; $i<= $days; $i++) {
                                $startDateArray[] = date('Y-m-d', strtotime("-{$i} day"));
                            }

                            $startDateArray = array_reverse($startDateArray);

                            foreach($startDateArray AS $startDate) {
                                $number  = WarehouseStockLogs::where([
                                    'log_date' => $startDate,
                                    'virtual_warehouse_id' => $val->virtual_warehouse_id,
                                    'goods_code' => $product->code,
                                    'batch_no' => $val->batch_no,
                                ])->value('number');

                                if ($number) {
                                    $fee = number_format($product->info->volume
                                    * $val->number
                                    * $storageConfig->fee, 2);

                                    $date1 = Carbon::parse($warehousingTime);
                                    $date2 = Carbon::parse($startDate);
                                    $diff = $date1->diffInDays($date2);
                                    StorageProductFee::create([
                                        'storage_fee_id' => $storageFee->id,
                                        'virtual_warehouse_id' => $val->virtual_warehouse_id,
                                        'goods_code' => $product->code,
                                        'goods_name' => $product->name_ch,
                                        'batch_no' => $val->batch_no,
                                        'storage_number' => $val->number,
                                        'warehousing_time' => $warehousingTime,
                                        'storage_days' => $diff+1,
                                        'fee' => $fee,
                                        'department_id' =>
                                            $val->department_id
                                    ]);
                                }
                            }
                        }
                    }
                }
            }
        }

        echo 'start-end:' .date('H:i:s') . "\r\n";
    }

}
